// Work in Progress
package com.premedsidekick;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class DefaultCursorAdapter extends CursorAdapter {
	Context context;
    int layout;
    DefaultDatabaseAdapter dbHelper;
    ArrayAdapter<CharSequence> arrayadapter;
    LayoutInflater inflater;
    View view;
    boolean check;
    
    public DefaultCursorAdapter (Context context, int layout, Cursor cursor, DefaultDatabaseAdapter dbHelper) {    	
        super(context, cursor);
        this.context = context;
        this.layout = layout;
        this.dbHelper = dbHelper;
        inflater = LayoutInflater.from(context);
    }
    public DefaultCursorAdapter (Context context, int layout, Cursor cursor) {
    	super(context, cursor);
        this.context = context;
        this.layout = layout;
        inflater = LayoutInflater.from(context);
    }
    public void initialize(DefaultDatabaseAdapter dbHelper, Cursor cursor) {
    	this.dbHelper = dbHelper;
    	super.changeCursor(cursor);
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
    	final Cursor c = cursor;
    	//c.moveToFirst();
        view = inflater.inflate(layout, parent, false);
        
        int id = c.getColumnIndex(dbHelper.KEY_ROWID);
        String key = c.getString(id);
        final int index = Integer.parseInt(key);
        System.out.println("Index retrieved: " + index);
        
        int nameCol = c.getColumnIndex(dbHelper.KEY_NAME);
        String name = c.getString(nameCol);
        System.out.println("Name retrieved: " + name);
        //System.out.println(name);
        final EditText edittext = (EditText)view.findViewById(R.id.edittext);
       	edittext.setText(name);
       	edittext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				edittext.selectAll();
			}
			
		});
       	/*
       	edittext.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				dbHelper.updateName(index, edittext.getText().toString());
	        	c.requery();
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}
       		
       	});
       	*/
       	edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
	        @Override
	        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	            if (actionId == EditorInfo.IME_ACTION_DONE) {
	            	dbHelper.updateName(index, edittext.getText().toString());
		        	c.requery();
	                return true;
	            }
	            return false;
	        }
	    });
       	/*
		edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				dbHelper.updateName(index, edittext.getText().toString());
	        	c.requery();
			}
			
		});
        edittext.setOnKeyListener(new OnKeyListener() {
		    public boolean onKey(View view, int keyCode, KeyEvent event) {
		        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
		            (keyCode == KeyEvent.KEYCODE_ENTER)) {
		        	dbHelper.updateName(index, edittext.getText().toString());
		        	c.requery();
		        	return true;
		        }
		        return false;
		    }
		});
		*/
        final Spinner spinner = (Spinner)view.findViewById(R.id.spinner);
        arrayadapter = ArrayAdapter.createFromResource(
	            context, R.array.hour_options, android.R.layout.simple_spinner_item);
        arrayadapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spinner.setAdapter(arrayadapter);
        int hourCol = c.getColumnIndex(dbHelper.KEY_HOURS);
        String hours = c.getString(hourCol);
        System.out.println("Hours retrieved: " + hours);
        int value = Integer.parseInt(hours);
        spinner.setSelection(value);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				Integer convert = new Integer(spinner.getSelectedItemPosition());
				boolean temp = dbHelper.updateHours(index, convert.toString());
				System.out.println("hours saved: " + temp);
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub	
			}
        });
        //final Cursor c = cursor;
        view.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View view) {
				AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
				builder.setMessage("Are you sure you want to delete this entry?")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dbHelper.delete(index);
				                c.requery();
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}
        });
        return view;
    }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
    	final Cursor c = cursor;
    	//c.moveToFirst();
    	int id = c.getColumnIndex(dbHelper.KEY_ROWID);
        String key = c.getString(id);
        final int index = Integer.parseInt(key);
        System.out.println("Index retrieved: " + index);
        
        int nameCol = c.getColumnIndex(dbHelper.KEY_NAME);
        String name = c.getString(nameCol);
        System.out.println("Name retrieved: " + name);
        final EditText edittext = (EditText)view.findViewById(R.id.edittext);
       	edittext.setText(name);
       	edittext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				edittext.selectAll();
			}
			
		});
       	/*
       	edittext.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				dbHelper.updateName(index, edittext.getText().toString());
	        	c.requery();
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				
			}
       		
       	});
       	*/
       	/*
       	edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
	        @Override
	        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	            if (actionId == EditorInfo.IME_ACTION_DONE) {
	            	dbHelper.updateName(index, edittext.getText().toString());
		        	c.requery();
	                return true;
	            }
	            return false;
	        }
	    });
	    */
       	/*
		edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				dbHelper.updateName(index, edittext.getText().toString());
	        	c.requery();
			}
			
		});
		*/
        edittext.setOnKeyListener(new OnKeyListener() {
		    public boolean onKey(View view, int keyCode, KeyEvent event) {
		        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
		            (keyCode == KeyEvent.KEYCODE_ENTER)) {
		        	dbHelper.updateName(index, edittext.getText().toString());
		        	c.requery();
		        	return true;
		        }
		        return false;
		    }
		});
        
        
        final Spinner spinner = (Spinner)view.findViewById(R.id.spinner);
        arrayadapter = ArrayAdapter.createFromResource(
	            context, R.array.hour_options, android.R.layout.simple_spinner_item);
        arrayadapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spinner.setAdapter(arrayadapter);
        int hourCol = c.getColumnIndex(dbHelper.KEY_HOURS);
        String hours = c.getString(hourCol);
        int value = Integer.parseInt(hours);
        System.out.println("Hours retrieved: " + hours);
        spinner.setSelection(value);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				Integer convert = new Integer(spinner.getSelectedItemPosition());
				boolean temp = dbHelper.updateHours(index, convert.toString());
				System.out.println("hours saved: " + temp);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub	
			}
        });
        //final Cursor c = cursor;
        view.setOnLongClickListener(new OnLongClickListener() {
        	
			@Override
			public boolean onLongClick(View view) {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
				builder.setMessage("Are you sure you want to delete this entry?")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dbHelper.delete(index);
				                c.requery();
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}
        });
    }
}
